package com.corpgovernment.common.utils;

import com.corpgovernment.common.constant.CommonConst;
import com.corpgovernment.common.holder.TenantContextHolder;
import com.google.common.base.Joiner;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author jhxue
 * @create 2021-12-21-17:33
 */
@Slf4j
public final class TenantUtils {

	private static final Joiner STRING_JOINER = Joiner.on("_");

	/**
	 * 占位符
	 */
	private static final String TENANT_SYMBOL = "[tenantId]";

	/**
	 * 是否为租户
	 *
	 * @return
	 */
	public static boolean isTenant() {
		String tenantId = TenantContextHolder.getTenantId();
		return !StringUtils.isBlank(tenantId);
	}

	/**
	 * 获取租户topic
	 *
	 * @param topic
	 * @return
	 */
	public static String getTenantTopic(String topic) {
		return addTenantPrefix(topic);
	}

	/**
	 * 获取租户group
	 *
	 * @param group
	 * @return
	 */
	public static String getTenantGroup(String group) {
		return addTenantPrefix(group);
	}

	/**
	 * 添加租户前缀
	 *
	 * @param str
	 * @return
	 */
	public static String addTenantPrefix(String str) {
		String tenantId = TenantContextHolder.getTenantId();
		return TenantUtils.isTenant() ? STRING_JOINER.join(tenantId, str) : str;
	}

	/**
	 * 替换URL中占位符
	 * 租户模式
	 * 请求前：https://biztravel.ctrip.com/${tenantId}/corp/admin
	 * 请求后：https://biztravel.ctrip.com/electricgroup/corp/admin
	 * 非租户模式
	 * 请求前：https://biztravel.ctrip.com/${tenantId}/corp/admin
	 * 请求后：https://biztravel.ctrip.com/corp/admin
	 * @param url
	 * @return
	 */
	public static String replaceTenant(String data){
		try {
			if (StringUtils.isNotBlank(data) && data.contains(TENANT_SYMBOL)){
				String tenantId = StringUtils.isNotBlank(TenantContextHolder.getTenantId()) ? TenantContextHolder.getTenantId() : "";
				return data.replace(TENANT_SYMBOL, tenantId);
			}
		} catch (Exception e){
			log.error("替换URL中占位符异常：{}", e);
		}
		return data;
	}

}
